package com.kallsonys.jsf;

import com.kallsonys.object.Customer;
import com.kallsonys.jsf.util.JsfUtil;
import com.kallsonys.jsf.util.PaginationHelper;
import com.kallsonys.object.Address;
import com.kallsonys.object.Creditcard;
import com.kallsonys.object.ws.ListElement;
import com.kallsonys.service.ElementListPage;
import com.kallsonys.session.AddressFacade;
import com.kallsonys.session.CreditcardFacade;
import com.kallsonys.session.CustomerFacade;

import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.ResourceBundle;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.component.UIComponent;
import javax.faces.component.html.HtmlDataTable;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import javax.faces.event.ActionEvent;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import javax.faces.model.SelectItem;

@ManagedBean(name = "customerController")
@SessionScoped
public class CustomerController implements Serializable {

    private Customer current;
    private DataModel items = null;
    @EJB
    private com.kallsonys.session.CustomerFacade ejbFacade;
    @EJB
    private com.kallsonys.session.AddressFacade addressFacade;
    @EJB
    private com.kallsonys.session.CreditcardFacade creditcardFacade;
    private PaginationHelper pagination;
    private int selectedItemIndex;
    private int pageSelected;   
    private int productId;
    private long customerId;
    private ElementListPage<com.kallsonys.service.Customer> lstPageCustomer;
    private Date startDate;
    private Date endDate;
    
    private String identificadorCliente;
    private String documentoCliente;

    public String getDocumentoCliente() {
        return documentoCliente;
    }

    public void setDocumentoCliente(String documentoCliente) {
        this.documentoCliente = documentoCliente;
    }

    public String getIdentificadorCliente() {
        return identificadorCliente;
    }

    public void setIdentificadorCliente(String identificadorCliente) {
        this.identificadorCliente = identificadorCliente;
    }
    
    
    
    

    public Date getEndDate() {
        return endDate;
    }

    public void setEndDate(Date endDate) {
        this.endDate = endDate;
    }

    public Date getStartDate() {
        return startDate;
    }

    public void setStartDate(Date startDate) {
        this.startDate = startDate;
    }
    
    private List<com.kallsonys.service.Customer> lstCustomer;

    public long getCustomerId() {
        return customerId;
    }

    public void setCustomerId(long customerId) {
        this.customerId = customerId;
    }
    
    public List<com.kallsonys.service.Customer> getLstCustomer() 
    {
        if (lstCustomer == null)
            lstCustomer = new ArrayList<com.kallsonys.service.Customer>();
        
        return lstCustomer;
    }

    public void setLstCustomer(List<com.kallsonys.service.Customer> lstCustomer) {
        this.lstCustomer = lstCustomer;
    }
    
    public int getPageSelected() {
        return pageSelected;
    }

    public void setPageSelected(int pageSelected) {
        this.pageSelected = pageSelected;
    }

    public ElementListPage<com.kallsonys.service.Customer> getLstPageCustomer() {
        return lstPageCustomer;
    }

    public void setLstPageCustomer(ElementListPage<com.kallsonys.service.Customer> lstPageCustomer) {
        this.lstPageCustomer = lstPageCustomer;
    }
    
    public CreditcardFacade getCreditcardFacade() {
        return creditcardFacade;
    }

    public void setCreditcardFacade(CreditcardFacade creditcardFacade) {
        this.creditcardFacade = creditcardFacade;
    }

    public Customer getCurrent() {
        return current;
    }

    public void setCurrent(Customer current) {
        this.current = current;
    }

    public CustomerFacade getEjbFacade() {
        return ejbFacade;
    }

    public void setEjbFacade(CustomerFacade ejbFacade) {
        this.ejbFacade = ejbFacade;
    }

    public int getProductId() {
        return productId;
    }

    public void setProductId(int productId) {
        this.productId = productId;
    }

    public int getSelectedItemIndex() {
        return selectedItemIndex;
    }

    public void setSelectedItemIndex(int selectedItemIndex) {
        this.selectedItemIndex = selectedItemIndex;
    }
    
    public CustomerController() {
    }

    public Customer getSelected() {
        if (current == null) {
            current = new Customer();
            selectedItemIndex = -1;
        }
        return current;
    }
    
    public String getCurrentLastCreditCard()
    {
        if (current != null && current.getLastusedcreditcardid() != null)
        {
            return current.getLastusedcreditcardid().getCreditcardnumber();
        }
        
        return "";
    }
    
    public String getCurrentLastAddress()
    {
        if (current != null && current.getLastusedaddressid() != null)
        {
            return current.getLastusedaddressid().getAddressstreet() + " "+ 
                    current.getLastusedaddressid().getAddresstown();
        }
        
        return "";
    }

    private CustomerFacade getFacade() {
        return ejbFacade;
    }

    private AddressFacade getAddressFacade() {
        return addressFacade;
    }

    private CreditcardFacade getCreditCardFacade() {
        return creditcardFacade;
    }

    public PaginationHelper getPagination() {
        if (pagination == null) {
            pagination = new PaginationHelper(10) {

                @Override
                public int getItemsCount() {
                    return getFacade().count();
                }

                @Override
                public DataModel createPageDataModel() {
                    return new ListDataModel(getFacade().findRange(new int[]{getPageFirstItem(), getPageFirstItem() + getPageSize()}));
                }
            };
        }
        return pagination;
    }

    public String prepareList() {
        recreateModel();
        return "List";
    }

    public String prepareView() {
        current = (Customer) getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        return "View";
    }
    
    public String prepareViewProduct() {
        current = ejbFacade.getByCustomerid(customerId);

        //selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        return "View";
    }
    
    public String creditcard() throws IOException {
        
        FacesContext.getCurrentInstance().getExternalContext().redirect("../creditcard/Create.xhtml");
        return "creditcard";
    }
    
     public String address() throws IOException {
        
        FacesContext.getCurrentInstance().getExternalContext().redirect("../address/Create.xhtml");
        return "address";
    }

    public String prepareCreate() {
        current = new Customer();
        selectedItemIndex = -1;
        return "Create";
    }

    public String create() {
        try {
            current.setCustomerid(Long.valueOf(0));
            getFacade().create(current);
            JsfUtil.addSuccessMessage("Cliente Creado");
            return prepareCreate();
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, "Error Creando el Cliente - Persistencia");
            return null;
        }
    }

    public String prepareEdit() {
        current = (Customer) getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        return "Edit";
    }

    public String update() {
        try {

            getFacade().edit(current);
            JsfUtil.addSuccessMessage("Cliente Modificado");
            return "View";
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, "Error Modificando el Cliente - Persistencia");
            return null;
        }
    }

    public String destroy() {
        current = (Customer) getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        performDestroy();
        recreateModel();
        return "List";
    }

    public String destroyAndView() {
        performDestroy();
        recreateModel();
        updateCurrentItem();
        if (selectedItemIndex >= 0) {
            return "View";
        } else {
            // all items were removed - go back to list
            recreateModel();
            return "List";
        }
    }

    private void performDestroy() {
        try {
            getFacade().remove(current);
            JsfUtil.addSuccessMessage("Cliente Eliminado");
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, "Error Eliminando el Cliente - Persistencia");
        }
    }

    private void updateCurrentItem() {
        int count = getFacade().count();
        if (selectedItemIndex >= count) {
            // selected index cannot be bigger than number of items:
            selectedItemIndex = count - 1;
            // go to previous page if last page disappeared:
            if (pagination.getPageFirstItem() >= count) {
                pagination.previousPage();
            }
        }
        if (selectedItemIndex >= 0) {
            current = getFacade().findRange(new int[]{selectedItemIndex, selectedItemIndex + 1}).get(0);
        }
    }

    public DataModel getItems() {
        if (items == null) {
            items = getPagination().createPageDataModel();
        }
        return items;
    }

    private void recreateModel() {
        items = null;
    }

    /**
     * Retorna las Categorias
     * @return 
     */
    public List<ListElement> getClientCategorys() {
        return getFacade().getClientCategorys();
    }

    public String getCurrentType() {
        String valorActual = String.valueOf(current.getCustomertype().intValue());
        String retorno = "";

        for (ListElement item : getClientCategorys()) {
            if (valorActual.equals(item.getElementId())) {
                retorno = item.getElementValue();
            }
        }

        return retorno;

    }

    public List<SelectItem> getClientCategorysItems() {
        List<SelectItem> lst = new ArrayList<SelectItem>();

        for (ListElement item : getClientCategorys()) {
            lst.add(new SelectItem(item.getElementId(), item.getElementValue()));
        }

        return lst;
    }

    public List<SelectItem> getClientAddress() {
        List<SelectItem> lst = new ArrayList<SelectItem>();
        if (current != null && current.getCustomerid() != null) {
            for (Address item : getAddressFacade().getByCustomerId(current.getCustomerid())) {
                lst.add(new SelectItem(item.getAddressid(), item.getAddressstreet() + "-" + item.getAddressphonenumber()));
            }
        }

        return lst;
    }
    
    public List<SelectItem> getClientCreditCard() {
        List<SelectItem> lst = new ArrayList<SelectItem>();
        if (current != null && current.getCustomerid() != null) {
            for (Creditcard item : getCreditCardFacade().getByCustomerId(current.getCustomerid())) {
                lst.add(new SelectItem(item.getCreditcardid(), item.getCreditcardnumber()));
            }
        }

        return lst;
    }

    public String next() {
        getPagination().nextPage();
        recreateModel();
        return "List";
    }

    public String previous() {
        getPagination().previousPage();
        recreateModel();
        return "List";
    }

    public SelectItem[] getItemsAvailableSelectMany() {
        return JsfUtil.getSelectItems(ejbFacade.findAll(), false);
    }

    public SelectItem[] getItemsAvailableSelectOne() {
        return JsfUtil.getSelectItems(ejbFacade.findAll(), true);
    }

    @FacesConverter(forClass = Customer.class)
    public static class CustomerControllerConverter implements Converter {

        public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
            if (value == null || value.length() == 0) {
                return null;
            }
            CustomerController controller = (CustomerController) facesContext.getApplication().getELResolver().
                    getValue(facesContext.getELContext(), null, "customerController");
            return controller.ejbFacade.find(getKey(value));
        }

        java.lang.Long getKey(String value) {
            java.lang.Long key;
            key = Long.valueOf(value);
            return key;
        }

        String getStringKey(java.lang.Long value) {
            StringBuffer sb = new StringBuffer();
            sb.append(value);
            return sb.toString();
        }

        public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
            if (object == null) {
                return null;
            }
            if (object instanceof Customer) {
                Customer o = (Customer) object;
                return getStringKey(o.getCustomerid());
            } else {
                throw new IllegalArgumentException("object " + object + " is of type " + object.getClass().getName() + "; expected type: " + CustomerController.class.getName());
            }
        }
    }

    public String viewProduct() throws Exception {
       lstPageCustomer = ejbFacade.getCustomersByProduct(productId, pageSelected);
       lstCustomer = lstPageCustomer.getElementList();
        return "";
    }
    
    
    public String viewRanking() throws Exception {
       lstPageCustomer = ejbFacade.getCustomersByBilling(startDate, endDate, pageSelected);
       lstCustomer = lstPageCustomer.getElementList();
        return "";
    }
    
    
    public String viewCustomerDocument() throws Exception {
       long idCustomerSearch = (identificadorCliente.trim().length() > 0 ? Long.valueOf(identificadorCliente) : -1);         
       lstPageCustomer = ejbFacade.getCustomersByDocument(idCustomerSearch,documentoCliente.trim());
       lstCustomer = lstPageCustomer.getElementList();
       return "";
    }
    
    public int getTotalPages()
    {
        int retorno = 0;
        if (lstPageCustomer != null)
        retorno = lstPageCustomer.getPages();
        return retorno;
    }
    
    
    
     public String editOrder(ActionEvent evt) throws IOException {
        // We get the table object
        HtmlDataTable table = getParentDatatable((UIComponent) evt.getSource());
        // We get the object on the selected line.
        Object o = table.getRowData();

        com.kallsonys.service.Customer customer = (com.kallsonys.service.Customer) o;
        
        customerId = customer.getId();

        current = new Customer(customer.getId());
        // Eventually, if you need the index of the line, simply do:
        //int index = table.getRowIndex();

        //FacesContext.getCurrentInstance().getExternalContext().redirect("../orderOms/View.xhtml");

        return "View";
        // ...
    }

// Method to get the HtmlDataTable.
    private HtmlDataTable getParentDatatable(UIComponent compo) {
        if (compo == null) {
            return null;
        }
        if (compo instanceof HtmlDataTable) {
            return (HtmlDataTable) compo;
        }
        return getParentDatatable(compo.getParent());
    }
}
